package com.hcl.security.config.username;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UsernameFilter extends AbstractAuthenticationProcessingFilter {

	/**
	 * 构造方法
	 *
	 * @param requiresAuthenticationRequestMatcher
	 *            请求匹配器
	 * @param authenticationManager
	 *            认证管理器
	 * @param successHandler
	 *            认证成功处理器
	 * @param failureHandler
	 *            认证失败处理器
	 */
	public UsernameFilter(RequestMatcher requiresAuthenticationRequestMatcher,
			AuthenticationManager authenticationManager,
			AuthenticationSuccessHandler successHandler,
			AuthenticationFailureHandler failureHandler) {
		super(requiresAuthenticationRequestMatcher, authenticationManager);
		super.setAuthenticationSuccessHandler(successHandler);
		super.setAuthenticationFailureHandler(failureHandler);
	}

	// 重写attemptAuthentication方法，提取参数
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UsernameForm usernameForm = new UsernameForm();
		usernameForm.setUsername(username);
		usernameForm.setPassword(password);
		return getAuthenticationManager()
				.authenticate(new UsernameAuthentication(usernameForm, null));
	}
}
